﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Text.RegularExpressions;

namespace MvcProject.Utils
{
    /// <summary>
    /// Email验证
    /// </summary>
    public sealed class ValidateEmailAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "请输入正确的{0}";
        public ValidateEmailAttribute() : base(_defaultErrorMessage) { }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
            name, _defaultErrorMessage);
        }
        public override bool IsValid(object value)
        {
            string email = value as string;
            if (String.IsNullOrEmpty(email))
                return false;
            string pattern = "^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.[a-zA-Z0-9_-])$";
            Regex reg = new Regex(pattern);
            return reg.IsMatch(email);
        }
    }
    /// <summary>
    /// 自定义验证
    /// </summary>
    public sealed class ValidateLongShareAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "请输入正确的{0}";
        public ValidateLongShareAttribute() : base(_defaultErrorMessage) { }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
            name, _defaultErrorMessage);
        }
        public string RegexString
        {
            get;
            set;
        }
        public override bool IsValid(object value)
        {
            string str = value as string;
            if (String.IsNullOrEmpty(str))
                return false;
            Regex reg = new Regex(RegexString);
            return reg.IsMatch(str);
        }
    }
}